// @ts-check

import { isObj } from "aomd-utils/src/Type";
import { AEvent } from "aomd-web-db/src/AEvent"
import { CacheBorderLoader } from "../CacheBorderLoader"
import { createXHR } from "../core/xhr"

export class RequestEntity extends AEvent {
  constructor(option) {
    super();

    if (!isObj(option)){
      throw new Error(`option This type is not object`)
    }

    this._event = {
      'error': [],
      'final': [],
      'success': [],
      'progress': [],
    }

    var thatOption = {
      ...option
    }
    this.xhr = createXHR()
    this.uid = CacheBorderLoader.sha256(thatOption['url'])
    this.url = thatOption['url'] || './'
    this.mime = thatOption['mime'] || 'any'

    // 超时时间 以时间戳表示
    this.expire = new Date(thatOption['expire']).getTime() || 0

    this.progress = 0

    this.status = false;

    this.size = 0;

    this.payloads = null;
  }

  send() {
    var xhr = this.xhr;
    xhr.open('get', this.url, true)
    xhr.responseType = 'blob'

    // 请求被终止
    xhr.addEventListener('abort', (e) => {
      console.log('abort')
      this.progress = 100;
      this._emit('error', { entity: this, e, type: 'abort' })
    })
    // 当 request 遭遇错误时触发
    xhr.addEventListener('error', (e) => {
      console.log('error')
      this.progress = 100;
      this._emit('error', { entity: this, e, type: 'error' })
    })

    // 接收到响应数据时触发。
    // xhr.addEventListener('loadstart', (e) => {
    //   /**this.size = e.total*/
    // })

    // 当请求结束时触发, 无论请求成功 ( load) 还是失败 (abort 或 error)
    xhr.addEventListener('loadend', (e) => {
      console.log('loadend')
      this.progress = 100;
      this._emit('final', { entity: this, e, type: 'loadend' })
    })

    // xhr.addEventListener('readystatechange')
    // 在预设时间内没有接收到响应时触发。
    xhr.addEventListener('timeout', (e) => {
      console.log('timeout')
      this.progress = 100;
      this._emit('error', { entity: this, e, type: 'timeout' })
    })


    // XMLHttpRequest请求成功完成时触发
    xhr.addEventListener('load', (e) => {
      console.log('load')
      var status = e.target['status']
      var contentType = e.currentTarget['getResponseHeader']('Content-Type');

      if (status === 200 && this.mime == 'any' ? true : this.mime == contentType) {
        this.progress = 100;

        this.payloads = e.target['response']
        this.status = true

        this._emit('success', { entity: this, e, type: 'load' })
      } else {
        // 异常
        this.progress = 100;
        this._emit('error', { entity: this, e, type: 'load' })
      }
    })

    // 当请求接收到更多数据时，周期性地触发。
    xhr.addEventListener('progress', (e) => {
      console.log('progress')

      this.size = e.total
      // 计算当前进度
      this.progress = (e.loaded / e.total) * 100
      this._emit('progress', { entity: this, e, type: 'progress' })
    })

    xhr.send()

  }
}
